package com.iisigroup.log.statistics.internal;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.iisigroup.log.model.LogRecordV1;

public class LogicProcessByThread {
    private final File dir;

    public LogicProcessByThread(final File dir) {
	this.dir = dir;
    }

    public void process(final LogRecordV1 unit) {
	final String account = unit.getAccount();
	String threadName = StringUtils.replace(unit.getThreadName(),":","").trim();
	if (StringUtils.isBlank(account)) {
	    return;
	}
	final Charset cs = Charset.forName("UTF-8");
	String dirPath = dir.getAbsolutePath()+"_wb";
	File newDir =new File(dirPath);
	try {
	    if (!newDir.exists()) {
		Files.createDirectories(newDir.toPath());
	    }

	    final Path outPath = Paths.get(dirPath, threadName);
	    List<String> lines = new ArrayList<String>(1);
	    lines.add(unit.getSrc());
	    if (Files.notExists(outPath)) {
		Files.write(outPath, lines, cs, StandardOpenOption.CREATE_NEW);
	    } else {
		Files.write(outPath, lines, cs, StandardOpenOption.APPEND);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
    } 
}
